import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { storageManager } from '@/utils/storage'

// 配置NProgress
NProgress.configure({ 
  showSpinner: false,
  minimum: 0.2,
  easing: 'ease',
  speed: 500
})

// 路由配置
const routes: RouteRecordRaw[] = [
  {
    path: '/share/knowledge/:token',
    name: 'KnowledgeSharePublic',
    component: () => import('@/views/knowledge/share.vue'),
    meta: {
      title: '知识库分享',
      requiresAuth: false,
      hideInMenu: true
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      title: '登录',
      requiresAuth: false,
      hideInMenu: true
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/register/index.vue'),
    meta: {
      title: '注册',
      requiresAuth: false,
      hideInMenu: true
    }
  },
  {
    path: '/',
    component: () => import('@/layouts/DefaultLayout.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: {
          title: '仪表盘',
          requiresAuth: true,
          icon: 'Odometer'
        }
      },
      {
        path: 'projects',
        name: 'ProjectManagement',
        component: () => import('@/views/projects/main.vue'),
        meta: {
          title: '项目管理',
          requiresAuth: true,
          permissions: ['project:read'],
          icon: 'FolderOpened'
        },
        children: [
          {
            path: ':id',
            name: 'ProjectDetail',
            component: () => import('@/views/projects/detail.vue'),
            meta: {
              title: '项目详情',
              requiresAuth: true,
              permissions: ['project:read'],
              hideInMenu: true,
              icon: 'View'
            }
          },
          {
            path: ':id/members',
            name: 'ProjectMembers',
            component: () => import('@/views/projects/members.vue'),
            meta: {
              title: '项目成员',
              requiresAuth: true,
              permissions: ['project:manage_members'],
              roles: ['admin', 'project_manager'],
              hideInMenu: true,
              icon: 'User'
            }
          }
        ]
      },
      {
        path: 'versions',
        name: 'Versions',
        component: () => import('@/views/versions/Main.vue'),
        meta: {
          title: '版本管理',
          requiresAuth: true,
          permissions: ['version:read'],
          icon: 'Box'
        }
      },
      {
        path: 'versions/planning',
        name: 'VersionsPlanning',
        component: () => import('@/views/versions/Planning.vue'),
        meta: {
          title: '版本规划',
          requiresAuth: true,
          permissions: ['version:read'],
          hideInMenu: true,
          icon: 'Guide'
        }
      },
      {
        path: 'requirements',
        name: 'Requirements',
        component: () => import('@/views/requirements/index.vue'),
        meta: {
          title: '需求管理',
          requiresAuth: true,
          permissions: ['requirement:read'],
          icon: 'Document'
        }
      },
      {
        path: 'tasks',
        name: 'Tasks',
        component: () => import('@/views/tasks/index.vue'),
        meta: {
          title: '任务管理',
          requiresAuth: true,
          permissions: ['task:read'],
          icon: 'List'
        }
      },
      {
        path: 'tasks/by-date',
        name: 'TasksByDate',
        component: () => import('@/views/tasks/by-date.vue'),
        meta: {
          title: '日期任务列表',
          requiresAuth: true,
          permissions: ['task:read'],
          hideInMenu: true,
          icon: 'Calendar'
        }
      },
      {
        path: 'defects',
        name: 'Defects',
        component: () => import('@/views/defects/index.vue'),
        meta: {
          title: '缺陷管理',
          requiresAuth: true,
          permissions: ['defect:read'],
          icon: 'Warning'
        }
      },
      {
        path: 'defects/:id',
        name: 'DefectDetail',
        component: () => import('@/views/defects/DefectDetail.vue'),
        meta: {
          title: '缺陷详情',
          requiresAuth: true,
          permissions: ['defect:read'],
          hideInMenu: true,
          icon: 'View'
        }
      },
      {
        path: 'test-management',
        name: 'TestManagement',
        redirect: '/test-management/cases',
        meta: {
          title: '测试管理',
          requiresAuth: true,
          permissions: ['test_case:read'],
          icon: 'DocumentChecked'
        },
        children: [
          {
            path: 'cases',
            name: 'TestCaseManagement',
            component: () => import('@/views/test-cases/index.vue'),
            meta: {
              title: '用例管理',
              requiresAuth: true,
              permissions: ['test_case:read'],
              icon: 'DocumentChecked'
            }
          },
          {
            path: 'plans',
            name: 'TestPlanManagement',
            component: () => import('@/views/test-plans/index.vue'),
            meta: {
              title: '测试计划',
              requiresAuth: true,
              permissions: ['test_case:read'],
              icon: 'Calendar'
            }
          },
          {
            path: 'plans/:id',
            name: 'TestPlanDetail',
            component: () => import('@/views/test-plans/TestPlanDetail.vue'),
            meta: {
              title: '测试计划详情',
              requiresAuth: true,
              permissions: ['test_case:read'],
              hideInMenu: true,
              icon: 'Calendar'
            }
          },
          {
            path: 'reports',
            name: 'TestReportManagement',
            component: () => import('@/views/test-reports/index.vue'),
            meta: {
              title: '测试报告',
              requiresAuth: true,
              permissions: ['test_case:read'],
              icon: 'Document'
            }
          }
        ]
      },
      {
        path: 'knowledge',
        name: 'Knowledge',
        component: () => import('@/views/knowledge/index.vue'),
        meta: {
          title: '知识库',
          requiresAuth: true,
          permissions: ['doc:read'],
          icon: 'Folder'
        }
      },
      {
        path: 'user-center',
        name: 'UserCenter',
        redirect: '/user-center/users',
        meta: {
          title: '用户中心',
          requiresAuth: true,
          permissions: ['user:read'],
          roles: ['admin'],
          icon: 'UserFilled'
        },
        children: [
          {
            path: 'users',
            name: 'Users',
            component: () => import('@/views/users/index.vue'),
            meta: {
              title: '用户管理',
              requiresAuth: true,
              permissions: ['user:read'],
              roles: ['admin'],
              icon: 'User'
            }
          },
          {
            path: 'roles',
            name: 'Roles',
            component: () => import('@/views/user-center/roles/index.vue'),
            meta: {
              title: '角色管理',
              requiresAuth: true,
              permissions: ['role:read'],
              roles: ['admin'],
              icon: 'Avatar'
            }
          },
          {
            path: 'permissions',
            name: 'Permissions',
            component: () => import('@/views/user-center/permissions/index.vue'),
            meta: {
              title: '权限管理',
              requiresAuth: true,
              permissions: ['permission:read'],
              roles: ['admin'],
              icon: 'Key'
            }
          },
          {
            path: 'team-members',
            name: 'TeamMembers',
            component: () => import('@/views/user-center/team-members/index.vue'),
            meta: {
              title: '项目成员管理',
              requiresAuth: true,
              permissions: ['project:manage_members'],
              roles: ['admin'],
              icon: 'UserFilled'
            }
          }
        ]
      },
      {
        path: 'system-management',
        name: 'SystemManagement',
        component: () => import('@/layouts/BlankLayout.vue'),
        meta: {
          title: '基础配置',
          requiresAuth: true,
          permissions: ['system:read'],
          roles: ['admin'],
          icon: 'Grid'
        },
        children: [
          {
            path: 'states',
            name: 'StateManagement',
            component: () => import('@/views/system/states/index.vue'),
            meta: {
              title: '状态管理',
              requiresAuth: true,
              permissions: ['state:view'],
              roles: ['admin'],
              icon: 'Operation'
            }
          },
          {
            path: 'priorities',
            name: 'PriorityManagement',
            component: () => import('@/views/system/priorities/index.vue'),
            meta: {
              title: '优先级管理',
              requiresAuth: true,
              permissions: ['priority:view'],
              roles: ['admin'],
              icon: 'Sort'
            }
          },
          {
            path: 'tags',
            name: 'TagManagement',
            component: () => import('@/views/system/tags/index.vue'),
            meta: {
              title: '标签管理',
              requiresAuth: true,
              permissions: ['tag:view'],
              roles: ['admin'],
              icon: 'Collection'
            }
          },
          {
            path: 'types',
            name: 'TypeManagement',
            component: () => import('@/views/system/types/index.vue'),
            meta: {
              title: '类型管理',
              requiresAuth: true,
              permissions: ['type:view'],
              roles: ['admin'],
              icon: 'List'
            }
          },
          {
            path: 'sources',
            name: 'SourceManagement',
            component: () => import('@/views/system/sources/index.vue'),
            meta: {
              title: '来源管理',
              requiresAuth: true,
              permissions: ['source:view'],
              roles: ['admin'],
              icon: 'Document'
            }
          }
        ]
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('@/views/settings/index.vue'),
        meta: {
          title: '系统设置',
          requiresAuth: true,
          permissions: ['system:read'],
          roles: ['admin'],
          icon: 'Setting'
        }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/profile/index.vue'),
        meta: {
          title: '个人中心',
          requiresAuth: true,
          hideInMenu: true,
          icon: 'UserFilled'
        }
      },
      {
        path: 'notifications',
        name: 'Notifications',
        component: () => import('@/views/notifications/index.vue'),
        meta: {
          title: '通知中心',
          requiresAuth: true,
          hideInMenu: true,
          icon: 'Bell'
        }
      }
    ]
  },
  {
    path: '/403',
    name: 'Forbidden',
    component: () => import('@/views/error/403.vue'),
    meta: {
      title: '访问被拒绝',
      requiresAuth: false,
      hideInMenu: true
    }
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/error/404.vue'),
    meta: {
      title: '页面不存在',
      requiresAuth: false,
      hideInMenu: true
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(_to, _from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 白名单路由（不需要登录验证）
const whiteList = ['/login', '/register', '/404', '/403']

// 全局前置守卫
router.beforeEach(async (to, _from, next) => {
  NProgress.start()
  
  try {
    const userStore = useUserStore()
    
    // 设置页面标题
    if (to.meta?.title) {
      document.title = `${to.meta.title} - 项目管理系统`
    }
    
    // 检查是否需要登录
    if (to.meta?.requiresAuth !== false && !whiteList.includes(to.path)) {
      // 如果还没有初始化且有 token，尝试初始化（initUserState 内部会防止重复初始化）
      const hasToken = storageManager.getItem('token')
      if (hasToken) {
        // initUserState 内部会检查是否已初始化，避免重复调用
        try {
          await userStore.initUserState()
        } catch (err) {
          console.error('初始化用户状态失败:', err)
          // 初始化失败，继续检查登录状态
        }
      }
      
      // 检查是否已登录（isLoggedIn 已包含 token 有效性检查）
      if (!userStore.isLoggedIn) {
        // 尝试刷新 token（可能 token 即将过期但还未过期）
        let refreshSuccess = false
        try {
          refreshSuccess = await userStore.refreshTokenIfNeeded()
        } catch (err) {
          console.error('刷新token失败:', err)
        }
        
        // 如果刷新失败或仍然未登录，跳转到登录页
        if (!refreshSuccess || !userStore.isLoggedIn) {
          ElMessage({
            message: '登录状态已失效，请重新登录',
            type: 'warning',
            duration: 1500
          })
          if (to.path !== '/login' && to.path !== '/register') {
            storageManager.setItem('redirectPath', to.path)
          }
          next('/login')
          return
        }
      }
      
      // 检查角色权限
      if (to.meta?.roles && Array.isArray(to.meta.roles) && to.meta.roles.length > 0) {
        const hasRole = to.meta.roles.some(role => userStore.hasRole(role))
        if (!hasRole) {
          ElMessage.error('权限不足')
          next('/403')
          return
        }
      }
      
      // 检查具体权限
      if (to.meta?.permissions && Array.isArray(to.meta.permissions) && to.meta.permissions.length > 0) {
        const isAdmin = userStore.hasPermission('*')
        const hasPermission = isAdmin || userStore.hasAnyPermission(to.meta.permissions)
        if (!hasPermission) {
          ElMessage.error('权限不足')
          next('/403')
          return
        }
      }
    } else {
      // 如果已登录用户访问登录页，重定向到首页或保存的路径
      if (to.path === '/login' && userStore.isLoggedIn) {
        const redirectPath = storageManager.getItem<string>('redirectPath') || '/dashboard'
        storageManager.removeItem('redirectPath')
        next(redirectPath)
        return
      }
    }
    
    // 允许继续导航
    next()
  } catch (error) {
    console.error('路由守卫错误:', error)
    // 即使出错也要调用next，避免导航卡住
    next()
  }
})

// 全局后置守卫
router.afterEach((to, from) => {
  // 结束进度条
  NProgress.done()
  
  // 记录路由跳转日志
  console.log(`路由跳转: ${from.path} -> ${to.path}`)
})

// 路由错误处理
router.onError((error) => {
  // 忽略重复导航和取消导航的错误
  if (error.name === 'NavigationDuplicated' || error.name === 'NavigationCancelled') {
    return
  }
  
  console.error('路由错误:', error)
  ElMessage.error('页面加载失败')
  NProgress.done()
})

export default router